import React, { useEffect, useState } from 'react';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import Header from './Header';
import LeaferCanvas from './LeaferCanvas';
import { isLeaferDragAtom } from './atoms';
import { useAtom } from 'jotai';

const LeaferEditor: React.FC = () => {
  // 创建一个状态用于存储屏幕高度
  const [screenHeight, setScreenHeight] = useState(window.innerHeight - 48);

  const [_, setIsLeaferDrag] = useAtom(isLeaferDragAtom);

  // 创建一个函数来处理窗口大小变化事件
  const handleResize = () => {
    console.log(window.innerHeight);
    setScreenHeight(window.innerHeight - 48);
  };

  // 使用 useEffect 来添加和移除事件监听器
  useEffect(() => {
    // 在组件挂载时添加事件监听器
    window.addEventListener('resize', handleResize);

    // 在组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []); // 传递一个空数组作为第二个参数，以确保只在组件挂载和卸载时运行

  return (
    <>
      <Header />
      <PanelGroup
        style={{ height: `${screenHeight}px`, minWidth: '1100px' }}
        direction="horizontal"
      >
        <Panel className="bg-slate-100" defaultSize={20} minSize={20}>
          left
        </Panel>
        <PanelResizeHandle
          className="w-2 bg-slate-100"
          onDragging={(isDragging: boolean) => {
            if(isDragging){
              setIsLeaferDrag(false);
            } else {
              setIsLeaferDrag(true);
            }
          }}
        />
        <Panel className="bg-red-100" minSize={30}>
          <LeaferCanvas />
        </Panel>
        <PanelResizeHandle className="w-2 bg-slate-100" />
        <Panel className="bg-slate-100" defaultSize={20} minSize={20}>
          right
        </Panel>
      </PanelGroup>
    </>
  );
};

export default LeaferEditor;
